import * as API_Trade from "../../../api/trade";
const util = require('../../../utils/util.js');
import regeneratorRuntime from '../../../lib/wxPromise.min.js'
const app = getApp();
import * as API_Connect from '../../../api/connect'
import * as API_Common from '../../../api/common'
import * as API_Member from '../../../api/members'
import * as API_Passport from '../../../api/passport'
import * as API_Distribution from '../../../api/distribution'
import {
  Foundation,
  RegExp
} from '../../../ui-utils/index.js'
Page({
  data: {
    uuid: '',
    code:'',
    /* username: '',
    password: '',
    code: '',
    captcha_url: '', */
    form: {
      mobile: "",
      sms_code: "",
    },
    // 默认不显示
    showWxAuth: true,
    /* 发送验证码 */
    initTip: '发送验证码',
    endTip: '重新获取',
    sufTip: '秒后重新获取',
    count_time: 60,
    disabled: false,
    message: '',
    interval: null,
    //初始化数据
    // code:"",
    // session_key:"",
    // //获取电话号码时取得的加密数据
    // encryptedData: "",
    // iv: "",
    showLogin: false, //显示授权框
    session_key: null,
    openid: null

  },
  onLoad(options) {
    var that = this
    this.setData({
      form: {
        mobile: "",
        sms_code: ""
      },
    });
    console.log(options);

    // 如果未授权 进行授权
    console.log(wx.getStorageSync('wxauth'))
    console.log('wxauth', wx.getStorageSync('wxauth'));

    if (wx.getStorageSync('wxauth')) {
      this.setData({
        showWxAuth: true
      })
    } else {
      this.setData({
        showWxAuth: false
      })
    }
    const uuid = wx.getStorageSync('uuid')
    /*  const _captcha_url = API_Common.getValidateCodeUrl(uuid, 'LOGIN') */
    this.setData({
      uuid: uuid,
      /* captcha_url: _captcha_url */
    })
    //console.log('uuid', uuid);

    wx.login({
      success: function (res) {
        var code = res.code;
        wx.setStorageSync('getcode', code)
        wx.getUserInfo({
          success: function (res) {
            that.globalData.userInfo = res.userInfo
            typeof cb == "function" && cb(that.globalData.userInfo)
          }
        })
        // 请求后台获取session_key
        wx.request({
          url: 'https://apibuyer.oupinguoji.cn/passport/mini-program/sessionKey',
          method: "get",
          data: {code} ,
          success: function (res) {
            wx.setStorageSync('open_id', res.data.openid)
            wx.setStorageSync('session_key', res.data.session_key)
          }
        })
      }
    })
  },

  onShow() {
    if (wx.getStorageSync('refresh_token')) {
      wx.switchTab({
        url: '/pages/ucenter/index/index'
      })
    }
  },
  syncMobile(e) {
    this.setData({
      "form.mobile": e.detail.value
    })
  },
  syncMobilSmsCode(e) {
    this.setData({
      "form.sms_code": e.detail.value
    })
  },
  //检测授权登录
  wxLoginAuth() {
    var that = this
    wx.getSetting({
      success(res) {
        console.log('res', res);
        if (res.authSetting['scope.userInfo']) {
          wx.setStorageSync('wxauth', true)
          //自动登录
          app.toAutoLogin()
          setTimeout(() => {
            if (wx.getStorageSync('refresh_token')) {
              // wx.switchTab({
              //   url: '/pages/ucenter/index/index'
              // })
            } else {
              that.setData({
                showWxAuth: true
              })
            }
          }, 1000)
        }
      }
    })
  },
  
  // 授权手机号
  getPhoneNumber(e){
    var self = this;
    // 允许后执行
    if (e.detail.errMsg == "getPhoneNumber:ok") {
      var params = {
          encrypted_data : e.detail.encryptedData,
          iv: e.detail.iv,
          session_key : wx.getStorageSync('session_key')
      }
      wx.request({
        url: 'https://apibuyer.oupinguoji.cn/passport/mini-program/phone/decrypt',
        data: params,
        method: 'POST',
        success: function (res) {
          var data = {
            mobile:res.data.phoneNumber,
          }
          API_Passport.loginBymini(wx.getStorageSync('uuid'),data).then(response => {
            console.log(response)
            wx.showToast({
              title: '登陆成功',
            })
            wx.setStorageSync('access_token', response.access_token)
            wx.setStorageSync('refresh_token', response.refresh_token)
            wx.setStorageSync('uid', response.uid)
            // 获取用户信息
            API_Member.getUserInfo().then(res => {
              wx.setStorageSync('user', res)
            })
            wx.switchTab({
              url: '/pages/ucenter/index/index'
            })
          })
        },
        fail: function (err) {
          console.log(err)
        }
      })
    }
  },

  // 
  //图片验证码
  /*  handleChangeCaptchalUrl() {
     this.setData({
       captcha_url: API_Common.getValidateCodeUrl(this.data.uuid, 'LOGIN'),
       code:''
     })
   }, */
  //获取验证码

  sendValidMobileSms() {
    wx.showLoading({
      mask: true
    })
    return new Promise((resolve, reject) => {
      const {
        mobile
      } = this.data.form
      console.log("mobile", mobile, this);
      if (!/^1[3456789]\d{9}$/.test(mobile)) {
        wx.showToast({
          title: '手机号码格式有误！',
          icon: 'none'
        })
        wx.hideLoading()
        return false
      }
      API_Passport.sendMobileLoginSms(mobile, '0000', this.data.uuid).then(() => {
        wx.showToast({
          title: '验证码发送成功'
        })
        wx.hideLoading()
        this.startCountDown()
        resolve()
      }).catch(e => {
        wx.hideLoading()
        reject()
      })
    })
  },
  /* 禁用 发送验证码 */
  startCountDown() {
    this.setData({
      disabled: true
    })
    this.data.interval = setInterval(() => {
      if (this.data.count_time > 1) {
        this.data.count_time--
        this.data.message = this.data.count_time + this.data.sufTip
        this.setData({
          count_time: this.data.count_time,
          message: this.data.message
        })
      } else {
        clearInterval(this.data.interval)
        this.setData({
          message: '重新发送',
          count_time: 60,
          disabled: false
        })
      }
    }, 1000)
  },
  //登录
  async accountLogin() {
    /* if (this.data.password.length < 1 || this.data.username.length < 1) {
      wx.showModal({
        title: '提示',
        content: '请输入用户名或密码',
        showCancel: false,
        confirmColor: '#f42424'
      });
      return false;
    } */
    const {
      mobile,
      sms_code
    } = this.data.form
    if (!/^1[3456789]\d{9}$/.test(mobile)) {
      wx.showToast({
        title: '手机号码格式有误！',
        icon: 'none'
      })
      return false
    }
    if (sms_code.length != 4) {
      wx.showToast({
        title: '请输入4位短信验证码',
        icon: 'none'
      })
      return false
    }
    // 登录绑定事件
    /* const params = {
      username: this.data.username,
      password: this.data.password,
      captcha: this.data.code
    } */
    let params = {
      mobile: this.data.form.mobile,
      sms_code: this.data.form.sms_code,
      uuid: this.data.uuid,
    }
    // 存储access_token refresh_token user
    const {
      access_token,
      refresh_token,
      uid
    } = await API_Connect.loginByMobileConnect(this.data.uuid, params).catch( /* this.handleChangeCaptchalUrl */ )

    wx.setStorageSync('access_token', access_token)
    wx.setStorageSync('refresh_token', refresh_token)
    wx.setStorageSync('uid', uid)
    // 获取用户信息
    const user = await API_Member.getUserInfo()
    wx.setStorageSync('user', user)
    // 获取购物车信息
    const cart_list = await API_Trade.getCarts()
    wx.setStorageSync('shoplist', cart_list)

    //获取可用金额
    const res = await API_Distribution.getAmount()
    wx.setStorageSync('can_rebate', res.message)
    //获取待分润金额
    const response = await API_Distribution.getFenrun()
    wx.setStorageSync('daifenrun', response.daifenrun)
    //获取欧币
    const oucoin = await API_Member.getPoints()
    wx.setStorageSync('oucoin', oucoin.consum_point)

    /* wx.navigateBack({ delta: 1 }) */
    wx.switchTab({
      url: '/pages/ucenter/index/index'
    })
  },
  bindUsernameInput(e) {
    this.setData({
      username: e.detail.value
    })
  },
  bindPasswordInput(e) {
    this.setData({
      password: e.detail.value
    })
  },
  // bindCodeInput(e) {
  //   this.setData({
  //     code: e.detail.value
  //   })
  // },


})